package com.tedu.boot.config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tedu.util.response.ResultVo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @date 2023/4/19
 * @author liuhuan
 */
@RestControllerAdvice(basePackages = {"com.tedu"})
public class ControllerResponseAdvice implements ResponseBodyAdvice<Object> {

    public ControllerResponseAdvice() {
        System.out.println("初始化成功");
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return !methodParameter.getParameterType().isAssignableFrom(ResultVo.class);
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
      if(methodParameter.getParameterType().equals(String.class)){
          ObjectMapper objectMapper=new ObjectMapper();
          try {
              return objectMapper.writeValueAsString(new ResultVo(data));
          } catch (JsonProcessingException e) {
              throw new RuntimeException(e);
          }
      }
      return new ResultVo(data);

    }
}
